using System;
using System.Collections.Generic;
using System.Text;
using FeedBurner.Utility;
using System.Web;
using System.Xml;

namespace FeedBurner.Operations
{
    internal class ModifyFeed
    {
        public Feed Modify(string username, string password, Feed feed)
        {
            StringBuilder Query = new StringBuilder
                (string.Format("?user={0}&password={1}", username, password));


            string feedstring = HttpUtility.UrlEncode(
                FeedWriter.GetFeedXml(feed, true, false), Encoding.UTF8);

            Query.AppendFormat("&feed={0}", feedstring);

            Feed result = GetFeed(DataManager.Post(Urls.ModifyUrl() + Query.ToString(), ""));

            return result;
        }

        private Feed GetFeed(string Output)
        {
            Feed result = new Feed();
            XmlDocument Xml = new XmlDocument();
            Xml.LoadXml(Output);

            if (Errors.CheckError(Xml))
            {
                XmlNode GlobalInfoNode =
                    Xml.SelectSingleNode("//rsp/feed");

                if (GlobalInfoNode != null)
                {
                    result.ID = Convert.ToInt64
                          (GlobalInfoNode.Attributes["id"].InnerText);
                    result.Title = GlobalInfoNode.Attributes["title"].InnerText;
                    result.Uri = GlobalInfoNode.Attributes["uri"].InnerText;
                }

                return result;
            }
            return null;
        }
    }
}
